package perf.data;

import java.util.ArrayList;
import java.util.List;

public class Function extends BaseItem<Linecosts,Sourcefile> {

	private int startLine = Integer.MAX_VALUE;
	private int stopLine = Integer.MIN_VALUE;
	
	//inline costs does not define what row they are attached to
	private List<InlineCost> inlined = new ArrayList<InlineCost>();
	
	public Function( String name ) {
		super( name );
	}
	
	public List<InlineCost> getInlineCost( ) {
		return inlined;
	}
	
	public int getStartLine( ) {
		return startLine;
	}
	
	public int getStopLine( ) {
		return stopLine;
	}
	
	public InlineCost getInlineCostInstance( Sourcefile dst, int destLine ) {
		String name = InlineCost.composeName( this, dst );
		
		for ( InlineCost i : inlined ) {
			if ( i.getName().equals( name ) ) {
				return i;
			}
		}
		InlineCost ic = new InlineCost( this, dst );
		inlined.add( ic );
		return ic;
	}
	
	public Linecosts getLinecostInstance( int line ) {
		Linecosts lc = findSibling( line + "" );
		
		if ( lc != null ) {
			return lc;
		} else {
			return add( new Linecosts( line ) );
		}
	}
	
	@Override
	protected Linecosts add( Linecosts costs ) {
		int line = costs.getLine();
		
		if ( line < startLine ) {
			startLine = line;
		}
		
		if ( line > stopLine ) {
			stopLine = line;
		}
		return super.add( costs );
	}
	
	@Override
	public long getCost(int costidx) {
		long cost = 0;
		for ( Linecosts lc : siblings() ) {
			cost += lc.getCost(costidx);
		}
		
		for ( InlineCost i : inlined ) {
			cost += i.getCost( costidx );
		}
		
		return cost;
	}

}
